package com.army.stock.web;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by zhangyong on 15/3/4.
 */
public class PermitInterceptor implements HandlerInterceptor {

    private final static Logger logger = LoggerFactory.getLogger(PermitInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        //过滤掉登录
        if (uri.indexOf("/login") > -1) {
            return true;
        }
        if (uri.startsWith("/images/") || uri.startsWith("/javascripts/") || uri.startsWith("/stylesheets/")) {
            return true;
        }
        HttpSession httpSession = request.getSession(false);
        if (httpSession != null) {
            String permits = (String) httpSession.getAttribute("username");
            if (StringUtils.isEmpty(permits)) {
                response.sendRedirect("/login");
                return false;
            }
        } else {
            response.sendRedirect("/login");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
